package com.general.framework.wukong.blockingQueue.interview;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Semaphore;

public class ArrayBlockingQueueDemoBySemaphore {
    public static void main(String[] args) {
        BlockingQueue<String> queue = new ArrayBlockingQueue<>(3);
        Semaphore produceSemaphore = new Semaphore(1);
        Semaphore consumeSemaphore = new Semaphore(0);
        Interviewer3 interviewer = new Interviewer3(queue, produceSemaphore, consumeSemaphore);
        Interviewee3 interviewee = new Interviewee3(queue, produceSemaphore, consumeSemaphore);
        new Thread(interviewer).start();
        new Thread(interviewee).start();
    }
}

class Interviewer3 implements Runnable {
    private final BlockingQueue<String> queue;
    private final Semaphore produceSemaphore;
    private final Semaphore consumeSemaphore;
    private int remainingTasks = 10;

    public Interviewer3(BlockingQueue<String> queue, Semaphore produceSemaphore, Semaphore consumeSemaphore) {
        this.queue = queue;
        this.produceSemaphore = produceSemaphore;
        this.consumeSemaphore = consumeSemaphore;
    }

    @Override
    public void run() {
        for (int i = 1; i <= 10; i++) {
            try {
                produceSemaphore.acquire();
                String candidate = "Candidate" + i;
                queue.put(candidate);
                System.out.println("已安排好了第 " + candidate + " 位候选者");
                consumeSemaphore.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Interviewee3 implements Runnable {
    private final BlockingQueue<String> queue;
    private final Semaphore produceSemaphore;
    private final Semaphore consumeSemaphore;

    public Interviewee3(BlockingQueue<String> queue, Semaphore produceSemaphore, Semaphore consumeSemaphore) {
        this.queue = queue;
        this.produceSemaphore = produceSemaphore;
        this.consumeSemaphore = consumeSemaphore;
    }

    @Override
    public void run() {
        try {
            for (int i = 1; i <= 10; i++) {
                consumeSemaphore.acquire();
                String candidate = queue.take();
                System.out.println("第 " + candidate + " 位候选者面试完毕");
                produceSemaphore.release();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}